package com.reder.practice.common.filter;

import com.alibaba.fastjson.JSON;
import com.reder.practice.common.dto.ServerResponse;
import com.reder.practice.common.enums.state.CommonState;
import com.reder.practice.common.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * 用户会话相关过滤器
 *
 * @author Fish
 * created by 2018-05-20 10:50
 */
/*@WebFilter(
        // 过滤全部 URL
        urlPatterns = "/*",

        // 设置不过滤的 URL 白名单
        initParams = {
                @WebInitParam(
                        name = "urlsWhiteList",
                        value = "/user/login;/user/register;/user/exists;/manager/login"
                )
        }
)*/
@Slf4j
public class SessionFilter implements Filter {

    // 不进行过滤的 URL 白名单
    private final Set<String> urlsWhiteList = new HashSet<>(8);

    public void init(FilterConfig config) throws ServletException {
        String[] urls = config.getInitParameter("urlsWhiteList").split(";");
        urlsWhiteList.addAll(Arrays.asList(urls));
        log.debug("不进行过滤的 URL 白名单：" + urlsWhiteList);
    }

    // 如果 URI 是不需要过滤的，就直接放行，返回 true
    private boolean shouldDoFilter(String uri) {
        return "".equals(uri) || urlsWhiteList.contains(uri);
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // 如果已经是登陆界面，就不用过滤了
        String currentUri = request.getRequestURI();
        log.debug(currentUri);

        // 如果 URI 是不需要过滤的或者是已经登录了，就直接放行
        if (shouldDoFilter(currentUri) || SessionUtil.hasLogin(request)) {
            chain.doFilter(request, response);
        } else {
            // 返回 JSON 响应
            response.addHeader("Content-Type", "application/json;charset=utf-8");
            response.getWriter().println(needLoginResponse());
        }
    }

    // 需要先登录的响应信息
    private String needLoginResponse() {
        return JSON.toJSONString(ServerResponse.response(CommonState.YOU_NEED_LOGIN_FIRST));
    }
}
